﻿using WSS.Models.Xt;
using WSS.Pub;

namespace WSS.BLL.Xt
{
    /// <summary>
    /// 序号表
    /// </summary
    public class XhbManager
    {
        private static readonly XhbManager _Instance;

        private XhbManager() { }

        static XhbManager()
        {
            _Instance = new XhbManager();
        }

        /// <summary>
        /// 写数据库
        /// </summary>
        /// <param name="model"></param>
        private void _insert(XT_XHB model)
        {
            DBState db = new DBState { Name = model.MAP_INSERT, Param = model, Type = ESqlType.INSERT };
            DB.Execute(db);
        }

        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="model"></param>
        private void _update(XT_XHB model)
        {
            DBState db = new DBState { Name = model.MAP_UPDATE, Param = model, Type = ESqlType.UPDATE };
            DB.Execute(db);
        }

        /// <summary>
        /// 取一条实体数据
        /// </summary>
        /// <param name="table_name">表名</param>
        /// <returns></returns>
        private XT_XHB GetOne(string table_name)
        {
            return DB.Load<XT_XHB, PK_XT_XHB>(new PK_XT_XHB { BM = table_name });
        }

        
        /// <summary>
        /// 取得指定表的新序号（原序号基础上加1）
        /// </summary>
        /// <param name="table_name"></param>
        /// <returns></returns>
        public string GetXh(string table_name)
        {
            if (string.IsNullOrEmpty(table_name)) { return ""; }

            XT_XHB xhb = GetOne(table_name);

            if (xhb == null || xhb.BM == null)
            {
                xhb = new XT_XHB { BM = table_name, DQZ = 1 };
                _insert(xhb);

                return "1";
            }

            long dqz = xhb.DQZ.HasValue ? xhb.DQZ.Value : 1;
            dqz = dqz + 1;

            xhb.DQZ = dqz;

            _update(xhb);

            return dqz.ToString();

        }


        /// <summary>
        /// 设置指定表的序号值，一般用于循环插入数据时
        /// </summary>
        /// <param name="table_name"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public void SetXh(string table_name, long value)
        {
            if (string.IsNullOrEmpty(table_name)) { return; }

            XT_XHB xhb = GetOne(table_name);

            if (xhb == null || xhb.BM == null)
            {
                xhb = new XT_XHB { BM = table_name, DQZ = value };
                _insert(xhb);
                return;
            }

            xhb.DQZ = value;
            _update(xhb);
        }

        public static XhbManager Instance
        {
            get { return _Instance; }
        }
    }
}